// by ssg 20230922
import { isEmptyVal } from '@/utils/is'
import { camelCase } from 'lodash-es'

export const sleep = (ms) => {
  return new Promise((resolve) => {
    setTimeout(resolve, ms)
  })
}

export const toNumber = (value: string, scale: number) => {
  if (!value) return void 0

  return scale > 0 ? parseFloat(value) : parseInt(value)
}

export const toBoolean = (value: string, defval: boolean) => {
  if (!value) return defval

  const falseVals = ['', 'null', '0', 'false', 'no', 'NO', 'f', 'F']
  if (falseVals.includes(value)) return false

  return true
}

export const toSize = (value?: string, defval?: string): string | number => {
  if (!value) return defval || '70%'

  if (value.indexOf('%') > 0) return value

  return parseInt(value)
}

export const filterEmptyVal = (params) => {
  const keys = Object.keys(params)
  for (const k in keys) {
    if (isEmptyVal(params[k])) delete params[k]
  }
}

/**
 * 往数组插入元素
 * @param el：要插入的元素
 * @param arr：目标数组
 * @param pos：插入数据的位置
 * @returns 返回新数组
 */
export const insertElToArr = (el, arr, pos) => {
  const len = arr.length
  if (pos == 0) {
    arr.unshift(el)
  } else if (pos >= len) {
    arr.push(el)
  } else {
    const tmp: string[] = []
    for (let i = 0; i <= len; i++) {
      tmp[i] = i < pos ? arr[i] : i == pos ? el : arr[i - 1]
    }
    arr = tmp
  }
  return arr
}

export function toCamelCase(s: string) {
  const items = s.split('.')
  let ret = ''
  for(const i in items) {
    const item = items[i]
    if(ret) ret += '.'
    ret += camelCase(item)
  }

  return ret;
}
